package com.share.order.handler;

import com.share.common.result.ResponseResult;
import com.share.constant.AuthSecurityConstants;
import com.share.util.common.ResponseUtils;
import jakarta.servlet.ServletException;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 自定义AuthenticationEntryPoint
 */
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

        if(authException instanceof InsufficientAuthenticationException){
            String accept = request.getHeader("accept");
            if(accept.contains(MediaType.TEXT_HTML_VALUE)){
                //如果是html请求类型，则返回登录页
                LoginUrlAuthenticationEntryPoint loginUrlAuthenticationEntryPoint = new LoginUrlAuthenticationEntryPoint("/login");
                loginUrlAuthenticationEntryPoint.commence(request,response,authException);
            }else {
                //如果是api请求类型，则返回json
                ResponseUtils.result(response, ResponseResult.fail(AuthSecurityConstants.REQUIRES_A_TOKEN_FOR_ACCESS));
            }
        }else if(authException instanceof InvalidBearerTokenException){
            ResponseUtils.result(response,ResponseResult.fail(AuthSecurityConstants.INVALID_OR_EXPIRED_TOKEN));
        }else{
            ResponseUtils.result(response,ResponseResult.fail(authException));
        }
    }
}
